#!/bin/bash
#Quickly add sounds from soundcloud to a directory for Internet synthesizing DJ mangle mashing
#start file from command line with: ./sc.sh
#wget is required, though a rewrite to curl works fine
 
which wget &>/dev/null
if ! [ $? -eq 0 ]; then  echo "wget is currently required (curl could replace it) Go install it! " && exit;
fi
 
cd ~/Podcasts
for (( ; ; ))
do
echo "what artist?"
read input
 
if [[ -z "$input" ]]; then
    echo "put an artist name here to search"
    break
fi
 
input="http://soundcloud.com/$input";
link=`wget "$input" -q --user-agent 'Mozilla/5.0' -O -`;
artist=`echo "$input" |  sed s/[https]*:[\/]*soundcloud\.com[\/]// | grep "[^\/]"`;
pages=`echo "$link" | tr '"' "\n" | grep "tracks?" | grep "page=" | awk -F= '{print $NF}' | sort -nu | tail -n 1`
this=`wget -q --user-agent='Mozilla/5.0' $input -O -`;
songs=`echo "$this" | grep 'streamUrl' | tr '"' "\n" | sed 's/\\u0026amp;/\&/' | grep 'http://media.soundcloud.com/stream/' | sed 's/\\\\//'`;
titles=`echo "$this" | grep 'title":"' | tr ',' "\n" | grep 'title' | cut -d '"' -f 4`
songcount=`echo "$songs" | wc -l`
 
  
if [ -z "$songs" ]; then
    echo "[!] No songs found at $input." && exit
fi
 
 
for (( songid=1; songid <= $songcount; songid++ ))
do
    title=`echo "$titles" | sed -n "$songid"p`
    echo  "$songid $title"
done
 
for (( ; ; ))
do
echo "Select a song, (d) download all,(q) quit search";
read -s songinput
songregex=`echo "$songinput" | grep '[0-9]'`;
 
if [[ "$songinput" = "d" ]]; then
 
    file=`ls | grep "$artist"`;
    if [ -z "$file" ]; then
        mkdir $artist;
    fi
    cd $artist;
 echo "download all";
 for (( songid=1; songid <= $songcount; songid++ ))
 do
     title=`echo "$titles" | sed -n "$songid"p`
     echo "[-] Downloading $title..."
     url=`echo "$songs" | sed -n "$songid"p`;
     wget -c -q -nc  --user-agent='Mozilla/5.0' -O "$title.mp3" $url;
 done
 elif [[ "$songinput" = "q" ]]
    then break
    elif [[ "$songregex" ]]; then
        mkdir -p $artist
        cd $artist
        title=`echo "$titles" | sed -n "$songregex"p`
        echo "[-] Downloading $title..."
        url=`echo "$songs" | sed -n "$songregex"p`;
        wget -c -q -nc  --user-agent='Mozilla/5.0' -O "$title.mp3" $url;
fi
done
done
